package com.igeek.health.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.igeek.health.entity.Checkitem;
import com.igeek.health.entity.Setmeal;
import com.igeek.health.entity.SetmealCheckgroup;
import com.igeek.health.mapper.SetmealCheckgroupMapper;
import com.igeek.health.mapper.SetmealMapper;
import com.igeek.health.service.ISetmealService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.igeek.health.vo.PageQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fengqq
 * @since 2024-08-26
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements ISetmealService {

    @Autowired
    private SetmealCheckgroupMapper setmealCheckgroupMapper;
    //添加套餐信息
    @Transactional
    @Override
    public boolean add(Integer[] checkgroupIds, Setmeal setmeal) {
        //1.插入套餐数据
        baseMapper.insert(setmeal);

        //2.根据套餐id 插入中间表setmeal_checkgroup
        Stream.of(checkgroupIds).forEach(checkgroupId->{
            SetmealCheckgroup setmealCheckgroup = new SetmealCheckgroup();
            setmealCheckgroup.setCheckgroupId(checkgroupId);
            setmealCheckgroup.setSetmealId(setmeal.getId());
            setmealCheckgroupMapper.insert(setmealCheckgroup);
        });
        return true;
    }

    @Transactional(readOnly = true)
    //根据条件分页查询套餐
    @Override
    public Page<Setmeal> findPage(PageQueryVO vo) {
        if(ObjectUtil.isEmpty(vo)){
            return null;
        }
        Integer currentPage = vo.getCurrentPage();
        Integer pageSize = vo.getPageSize();
        String queryString = vo.getQueryString();

        //封装page对象
        Page<Setmeal> page = new Page<>(currentPage, pageSize);
        //封装条件
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.or().eq(StringUtils.hasLength(queryString),Setmeal::getCode,queryString);
        queryWrapper.or().like(StringUtils.hasLength(queryString),Setmeal::getName,queryString);
        queryWrapper.or().like(StringUtils.hasLength(queryString),Setmeal::getHelpCode,queryString);

        //执行分页查询
        Page<Setmeal> resultPage = this.baseMapper.selectPage(page, queryWrapper);
        return resultPage;
    }

    //套餐详情查询
    @Transactional(readOnly = true)
    @Override
    public Setmeal findOneDetail(Integer id) {
        Setmeal setmeal = setmealCheckgroupMapper.selectDetailById(id);
        return setmeal;
    }
}
